class Chapter < ActiveRecord::Base
  has_many :comics
  belongs_to :story
  
  def before_save
    if self.story_id.nil?
      self.story_id = Story.default.id
    end
    if !(s = Story.find_by_id(self.story_id))
      Story.create :id=>self.story_id, :title=>"New Story"
    end    
  end
  
  def after_create
    XmlFile.insert_chapter(self)
  end  
  
  def self.default
    self.find_or_create_by_name("Chapter 1")
  end
  
  def to_hash #for initialization only; pages aren't in order
    {
      :comics=>comics.collect{|c|c.to_hash},
      :attributes=>self.attributes,
      :id=>id
    }
  end  
  
  def xml_from_hash #returns an xml
    str = self.to_hash.to_xml
    parser = LibXML::XML::Parser.string(str)
    doc = parser.parse       
    doc.root.name="chapter"
    return doc.root
  end  
end
